function BLE (){}
var main, BAdapter, BluetoothAdapter, BluetoothDevice,BManager,Context;
var result = [];//蓝牙设备list
var bleStateChange = '';//链接状态
var bluetoothState = [];//设备蓝牙模块状态
var mac,serviceUUID,characteristicUUID;
//打开蓝牙模块
BLE.openBluetooth = function(){
	var that = this;
	main = plus.android.runtimeMainActivity();
	Context = plus.android.importClass("android.content.Context");
	BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
	plus.android.importClass("java.lang.String");
	BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
	BAdapter = BluetoothAdapter.getDefaultAdapter();
	if (!BAdapter.isEnabled()) {
		BAdapter.enable(); //启动蓝牙
		console.log('open Bluetooth failed');
	}else{
		console.log('open Bluetooth success');
	}
}

// 获取蓝牙状态
BLE.getBluetoothState = function(callback){
	plus.bluetooth.getBluetoothAdapterState({
		success:function(e){
			console.log('state success: '+JSON.stringify(e));
			callback('success');
		},
		fail:function(e){
			console.log('state failed: '+JSON.stringify(e));
			bluetoothState = e;
			callback('fail');
			CommonUtil.setStorage('bleSta','');
			CommonUtil.setStorage('mac','');
			CommonUtil.setStorage('serviceUUID','');
			CommonUtil.setStorage('characteristicUUID','');
		}
	});
}

//// 开始搜索蓝牙
BLE.startBluetoothDiscovery = function(){
	plus.bluetooth.openBluetoothAdapter({
		success:function(e){
			BLE.searchBluetooth();
		},
		fail:function(e){
			BLE.openBluetooth();
		}
	});
}

//搜索蓝牙
BLE.searchBluetooth = function(){
	// 设置延时，防止蓝牙未完全开启时调用
	CommonUtil.WaitFor(
	    function() {
	        return BAdapter.isEnabled();
	    },
	    function() {
	        // 获取已连接设备列表
	        plus.bluetooth.startBluetoothDevicesDiscovery({
	        	success:function(e){
	        		console.log('start discovery success: '+JSON.stringify(e));
	        		mui.toast('搜索蓝牙设备');
	        	},
	        	fail:function(e){
	        		mui.toast('搜索蓝牙设备失败');
	        		console.log('start discovery failed: '+JSON.stringify(e));
	        	}
	        });
	    },
	    3000);
	BLE.listenerDeviceFound();
}

// 监听发现新设备
BLE.listenerDeviceFound = function(){
	plus.bluetooth.onBluetoothDeviceFound(function(e){
		var devices = e.devices;
		
		for(var i in devices){
			if(devices[i].advertisServiceUUIDs != ''){
				//console.log('ble list'+i+': '+JSON.stringify(devices[i].localName));
				result.push(e)
			}
		}
	});
}

//链接蓝牙设备
BLE.createConnection = function(deviceId,name,callback){
	deviceId = deviceId;
	mui.toast('正在链接蓝牙设备...')
	plus.bluetooth.createBLEConnection({
		deviceId:deviceId,
		success:function(e){
			console.log('create connection success: '+JSON.stringify(e));
			mui.toast('成功链接蓝牙设备:'+name);
			CommonUtil.setStorage('bleSta',true);
			bleStateChange = 'linking';
			BLE.getServices(deviceId);
			BLE.stopBluetoothDiscovery();
			callback(bleStateChange);
		},
		fail:function(e){
			bleStateChange = 'unlink';
			callback(bleStateChange);
			console.log('create connection failed: '+JSON.stringify(e));
		}
	});
	
}
//停止搜索
BLE.stopBluetoothDiscovery = function(){
	plus.bluetooth.stopBluetoothDevicesDiscovery({
		success: function(e){
			console.log('停止搜索成功! '+JSON.stringify(e));
		},
		fail: function(e){
			console.log('停止搜索失败! '+JSON.stringify(e));
		}
	});
}
//断开链接
BLE.closeConnection = function(deviceId){
	plus.bluetooth.closeBLEConnection({
		deviceId:deviceId,
		success:function(e){
			console.log('close success: '+JSON.stringify(e));
		},
		fail:function(e){
			console.log('close failed: '+JSON.stringify(e));
		}
	});
}

//监听低功耗蓝牙设备连接状态变化 
BLE.BLEConnectionStateChange = function(callback){
	plus.bluetooth.onBLEConnectionStateChange(function(e){
		console.log('onBLEConnectionStateChange: '+JSON.stringify(e));
		if(!e.connected){
			//mui.toast('蓝牙设备断开');
			//BLE.openBluetooth();
			CommonUtil.setStorage('bleSta','');
			CommonUtil.setStorage('mac','');
			CommonUtil.setStorage('serviceUUID','');
			CommonUtil.setStorage('characteristicUUID','');
		}
		callback(e.connected);
	});
}

// 获取蓝牙设备的所有服务
BLE.getServices = function(deviceId){
	setTimeout(function(){
		plus.bluetooth.getBLEDeviceServices({
			deviceId:deviceId,
			success:function(e){
				var services = e.services;
				console.log('get services success: '+services.length);
				for(var i in services){
					//console.log(i+': '+JSON.stringify(services[i]));
					getCharacteristics(deviceId,services[i].uuid);
				}
			},
			fail:function(e){
				console.log('get services failed: '+JSON.stringify(e));
			}
		});
	}, 2000);
}

// 获取蓝牙设备指定服务中所有特征值
function getCharacteristics(deviceId,serviceId){
	plus.bluetooth.getBLEDeviceCharacteristics({
		deviceId:deviceId,
		serviceId:serviceId,
		success:function(e){
			var characteristics = e.characteristics;
			for(var i in characteristics){
				if(characteristics[i].properties.read && characteristics[i].properties.write && characteristics[i].properties.notify ){
					mac = deviceId;
					serviceUUID = serviceId;
					characteristicUUID = characteristics[i].uuid;
					CommonUtil.setStorage('mac',deviceId);
					CommonUtil.setStorage('serviceUUID',serviceId);
					CommonUtil.setStorage('characteristicUUID',characteristics[i].uuid);
				}
			}
		},
		fail:function(e){
			console.log('get characteristics failed: '+JSON.stringify(e));
		}
	});
}

//
BLE.notifyBLECharacteristicValueChange = function(deviceId,serviceId,characteristicId){
	plus.bluetooth.notifyBLECharacteristicValueChange({
		deviceId:deviceId,
		serviceId:serviceId,
		characteristicId:characteristicId,
		success:function(e){
			console.log('get characteristics success: '+JSON.stringify(e));
		},
		fail:function(e){
			console.log('get characteristics failed: '+JSON.stringify(e));
		}
	});
}

//发送数据
BLE.sendBuffer = function(str,callback){
	let strArry = BLE.split_array(str.split(" "),20);
	for(let i in strArry){
		let buffer = BLE.getBuffer(strArry[i].toString());
		//写入值
		BLE.writeCharacteristics(buffer,function(data){
			console.log(data);
		})
	}
	
}

//获取写入值
BLE.getBuffer = function(str){
	let bLen = str.length;
	let buffer = new ArrayBuffer(bLen);
	let iv = new Uint8Array(buffer);
	let val = str.split(",");
	for(let i=0;i<str.split(",").length;i++){
		iv[i] = "0x"+val[i];
	}
	return buffer;
}

// 写入低功耗蓝牙设备的特征值
BLE.writeCharacteristics = function(buffer,callback){
	mac = CommonUtil.getStorage('mac') ;
	serviceUUID = CommonUtil.getStorage('serviceUUID');
	characteristicUUID = CommonUtil.getStorage('characteristicUUID');
	plus.bluetooth.writeBLECharacteristicValue({
		deviceId:mac,
		serviceId: serviceUUID,
		characteristicId:characteristicUUID,
		value:buffer,
		success:function(e){
			console.log('write characteristics success: '+JSON.stringify(e));
			callback(JSON.stringify(e));
		},
		fail:function(e){
			console.log('write characteristics failed: '+JSON.stringify(e));
			callback(JSON.stringify(e));
		}
	});
}

//监听特征变化
BLE.onBLECharacteristicValueChange = function(va,callback){
	// 监听低功耗蓝牙设备的特征值变化 
	let result = '';
	plus.bluetooth.onBLECharacteristicValueChange(function(e){
		let value = BLE.buffer2hex(e.value);
		let data = "";
		let len = value.length;
		for (let i = 0; i < len; i += 2) {
			data += value.substring(i, (i + 2) > len ? len : (i + 2)) + " ";
		}
		result = result + data;
		//console.log(data);
		if(characteristicUUID != e.characteristicId){
			// 更新到页面显示
			console.log('特征值变化: ');
		}
	});
	setTimeout(function() {
		console.log(result);
		callback(result);
	}, va*500);
	BLE.notifyBLECharacteristicValueChange(mac,serviceUUID,characteristicUUID);
}

BLE.buffer2hex = function(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
//重新划分数组
BLE.split_array = function(arr, len) {
	var a_len = arr.length;
	var result = []
	for (var i = 0; i < a_len; i += len) {
		result.push(arr.slice(i, i + len))
	}
	return result;
}

